package com.qsl.web;

import com.qsl.manager.FileUploadManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 文件上传 controller
 * @author 青石路
 */
@RestController
@RequestMapping("file")
public class FileUploadController {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileUploadController.class);

    @Autowired
    private FileUploadManager fileUploadManager;

    @GetMapping("upload")
    public boolean upload(@RequestParam("fileName") String fileName) {
        long ramdomLong = ThreadLocalRandom.current().nextLong();
        File file = new File(System.getProperty("java.io.tmpdir") + File.separator + ramdomLong + ".txt");
        LOGGER.info("localFile:{}", file.getAbsoluteFile());
        boolean uploadResult;
        try {
            Files.write(file.toPath(), String.valueOf(ramdomLong).getBytes(StandardCharsets.UTF_8));
            uploadResult = fileUploadManager.uploadFileToSftp(file, fileName, true);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                Files.deleteIfExists(file.toPath());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return uploadResult;
    }
}